package com.scirillo.frases.ui;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.actionbarsherlock.widget.ShareActionProvider.OnShareTargetSelectedListener;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.scirillo.frases.BaseActivity;
import com.scirillo.frases.R;
import com.scirillo.frases.notification.FrasesNotificationManager;
import com.scirillo.frases.preference.FrasesPreferenceManager;
import com.scirillo.frases.service.AlarmService;
import com.scirillo.frases.service.NotifyService;
import com.scirillo.frases.util.Constants;
import com.scirillo.frases.util.ImageManager;
import com.scirillo.frases.util.ImagesTextWriter;
import com.scirillo.frases.util.Util;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ViewPagerFragmentActivity extends BaseActivity{
    public ViewPagerFragmentActivity() {
		super(R.string.app_name);
		// TODO Auto-generated constructor stub
	}

	private static String currentFrase;
	/** maintains the pager adapter*/
    private PagerAdapter mPagerAdapter;
  //  PageIndicator mIndicator;
    private List<Integer> backList = new ArrayList<Integer>();
    private List<Integer> love_backList = new ArrayList<Integer>();
    private List<Integer> frindship_backList = new ArrayList<Integer>();
    private List<Integer> art_backList = new ArrayList<Integer>();
    private List<Integer> art_paint_backList = new ArrayList<Integer>();
    private List<Integer> art_music_backList = new ArrayList<Integer>();
    private List<Integer> art_literature_backList = new ArrayList<Integer>();
    private List<Integer> mother_backList = new ArrayList<Integer>();
	private String[] frases;
	private AdView adView;
    private ShareActionProvider mShareActionProvider;
    private LinearLayout mViewpagerLayout;
    /* (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
     */
	private boolean hide;
	private final int FILE_BROWSING = 1;
	private ImageView mPostImage; 
    private byte[] fileBuffer;
    String filePath;
	BitmapDrawable bmd;
    private Bitmap bm1;
    
    @Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Util.getInstance().setCurrentContext(this);   
        super.setContentView(R.layout.viewpager_layout);
        mViewpagerLayout = (LinearLayout) findViewById(R.id.viewpager_layout);
		mPostImage = new ImageView(getApplicationContext());
    	mViewpagerLayout.setBackgroundDrawable((getResources().getDrawable(R.drawable.img01)));
		frases = getResources().getStringArray(R.array.frases);
		createBackList();
        this.initialisePaging();
        currentFrase = frases[0];
       // Intent myIntent = new Intent(this, NotifyService.class);  
       // startService(myIntent);
        AlarmService an = new AlarmService(this);
        an.startAlarm();
        createAd();
    }    
    
	private void createBackList() {
		//GENERAL
		backList.add(R.drawable.img01);
		backList.add(R.drawable.img02);
		backList.add(R.drawable.img03);
		backList.add(R.drawable.img04);
		backList.add(R.drawable.img05);
		backList.add(R.drawable.img06);
		backList.add(R.drawable.img07);
		backList.add(R.drawable.img08);
		backList.add(R.drawable.img09);
		backList.add(R.drawable.img010);
		backList.add(R.drawable.img011);
		backList.add(R.drawable.img013);
		backList.add(R.drawable.img14);
		backList.add(R.drawable.img15);
		backList.add(R.drawable.img16);
		backList.add(R.drawable.img17);
		backList.add(R.drawable.img18);	
		//LOVE IMGS
		love_backList.add(R.drawable.img_l1);
		love_backList.add(R.drawable.img_l2);
		love_backList.add(R.drawable.img_l3);
		love_backList.add(R.drawable.img_l4);
		love_backList.add(R.drawable.img_l5);
		love_backList.add(R.drawable.img_l6);
		love_backList.add(R.drawable.img_l7);
		love_backList.add(R.drawable.img_l8);
		love_backList.add(R.drawable.img_l9);
		//FRINDSHIP IMGS
		frindship_backList.add(R.drawable.img_f0);
		frindship_backList.add(R.drawable.img_f1);
		frindship_backList.add(R.drawable.img_f2);
		frindship_backList.add(R.drawable.img_f3);
		frindship_backList.add(R.drawable.img_f4);
		frindship_backList.add(R.drawable.img_f5);
		frindship_backList.add(R.drawable.img_f6);
		frindship_backList.add(R.drawable.img_f7);
		frindship_backList.add(R.drawable.img_f8);
		frindship_backList.add(R.drawable.img_f9);
		//LITERATURE IMGS
		art_literature_backList.add(R.drawable.img_al1);
		art_literature_backList.add(R.drawable.img_al2);
		art_literature_backList.add(R.drawable.img_al3);
		art_literature_backList.add(R.drawable.img_al4);
		art_literature_backList.add(R.drawable.img_al5);
		art_literature_backList.add(R.drawable.img_al6);
		art_literature_backList.add(R.drawable.img_al7);
		//MUSIC IMGS
		art_music_backList.add(R.drawable.img_am1);
		art_music_backList.add(R.drawable.img_am2);
		art_music_backList.add(R.drawable.img_am3);
		art_music_backList.add(R.drawable.img_am4);
		art_music_backList.add(R.drawable.img_am5);
		art_music_backList.add(R.drawable.img_am6);
		art_music_backList.add(R.drawable.img_am7);
		art_music_backList.add(R.drawable.img_am8);
		art_music_backList.add(R.drawable.img_am9);
		//PAINT IMGS
		art_paint_backList.add(R.drawable.img_ap1);
		art_paint_backList.add(R.drawable.img_ap2);
		art_paint_backList.add(R.drawable.img_ap3);
		art_paint_backList.add(R.drawable.img_ap4);
		art_paint_backList.add(R.drawable.img_ap5);
		art_paint_backList.add(R.drawable.img_ap6);
		art_paint_backList.add(R.drawable.img_ap7);
		art_paint_backList.add(R.drawable.img_ap8);
		art_paint_backList.add(R.drawable.img_ap9);
		//MOTHER
		mother_backList.add(R.drawable.img_m1);
		mother_backList.add(R.drawable.img_m2);
		mother_backList.add(R.drawable.img_m3);
		mother_backList.add(R.drawable.img_m4);
		mother_backList.add(R.drawable.img_m5);

	}

	private void createAd() {
		if(Constants.AD_ENABLED){
			LinearLayout layout = (LinearLayout)findViewById(R.id.main_layout);	  
		    adView = new AdView(this, AdSize.SMART_BANNER, Constants.AD_UNIT_ID);
		    // Add the adView to it
		    layout.addView(adView);

		    // Initiate a generic request to load it with an ad
			adView.loadAd(new AdRequest());
		}
	}
    
    
    
    @SuppressLint("NewApi")
	@Override
    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    	   // Inflate menu resource file.
        getSupportMenuInflater().inflate(R.menu.share_action_provider, (Menu) menu);
        // Locate MenuItem with ShareActionProvider
//        MenuItem item = (MenuItem) menu.findItem(R.id.menu_item_share);
//   
//        // Fetch and store ShareActionProvider
//  
//    //     	if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//    		mShareActionProvider = (ShareActionProvider) item.getActionProvider();    		
//    	
//    		mShareActionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
//            mShareActionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
//            	   boolean changeIntent = true;
//				@Override
//				public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {				
//					if(intent.getComponent().getPackageName().equalsIgnoreCase("com.facebook.katana")){				
//							 Toast.makeText(getApplicationContext(), "La frase fue copiado en el portapapeles", Toast.LENGTH_LONG).show();
//							 ClipboardManager clipboard = (ClipboardManager) (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
//							 String s = intent.getExtras().getString(Intent.EXTRA_TEXT);							 
//							 clipboard.setText(s);	 
//							 new ShowTextTask().execute("");
//					// 
//					}
//				    startActivity(intent);
//					return true;
//				}				
//			});
    //	}			
		
        // Return true to display menu
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	 switch (item.getItemId()) {
         case R.id.menu_item_enabletheme:
        	 hide = !hide;
      		 changeImageBack();
             return true;
         case R.id.menu_item_share:
        	
        	 new LoadImageTask().execute("");
             return true;
        // case R.id.menu_item_up:
      		//insertFile();
          //   return true;
		default:
			break;
		}
    	return super.onOptionsItemSelected(item);
    }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);			
		recreateAd();
	}
    
    private void recreateAd() {
    	if(Constants.AD_ENABLED){
	        LinearLayout layout = (LinearLayout)findViewById(R.id.main_layout);
		    layout.removeView(adView);
			 if (adView != null) {
			    	adView.destroy();
			      }
			   adView = new AdView(this, AdSize.SMART_BANNER, Constants.AD_UNIT_ID);
		    // Add the adView to it
		    layout.addView(adView);
			adView.loadAd(new AdRequest());
    	}
	}


    @Override
    protected void onStart() {
    	FrasesNotificationManager.clearNotifications();
    	if(Settings.updateFragments){
    		initialisePaging();
    	}
    	super.onStart();
    }
	
    /**
     * Initialise the fragments to be paged
     */
    private void initialisePaging() {
 
        final List<Fragment> fragments = new Vector<Fragment>();
    	for(int i = 0; i < frases.length ; i++){        	       
        	fragments.add(new FrasesFragment(i));	
        }
        this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);  
        final ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
        pager.setAdapter(this.mPagerAdapter);
        pager.setOnPageChangeListener(new OnPageChangeListener() {
    		@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageSelected(int pos) {
				switch (pos) {
				case 0:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
					break;
				default:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
					break;
				}		
				currentFrase = frases[pos];				
				changeImageBack();									
			}
			
	
		});
       
        pager.setCurrentItem(0);
      /* mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
        mIndicator.setViewPager(pager);    		    	*/
    	getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);    	
    	//setSlidingActionBarEnabled(false);
    }
    
  
	@SuppressWarnings("deprecation")
	private void changeImageBack(){		
		Random r = new Random();
	
		if(hide){					
			mViewpagerLayout.setBackgroundDrawable(null);	
			mViewpagerLayout.setBackgroundColor(getResources().getColor(R.color.back));
		}else{
			if(currentFrase.contains(Constants.LOVE)){
				int i1 = r.nextInt(love_backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(love_backList.get(i1)));
			}else if(currentFrase.contains(Constants.FRIENDSHIP)){
				int i1 = r.nextInt(frindship_backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(frindship_backList.get(i1)));
			}else if(currentFrase.contains(Constants.HOPE)){
				int i1 = r.nextInt(mother_backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(mother_backList.get(i1)));
			}else if(currentFrase.contains(Constants.MOM)){
				int i1 = r.nextInt(art_backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(art_backList.get(i1)));
			}else if(currentFrase.contains(Constants.ART_LITERATURE)){
				int i1 = r.nextInt(art_literature_backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(art_literature_backList.get(i1)));
			}else if(currentFrase.contains(Constants.ART_MUSIC)){
				int i1 = r.nextInt(art_music_backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(art_music_backList.get(i1)));
			}else if(currentFrase.contains(Constants.ART_PAINT)){
				int i1 = r.nextInt(art_paint_backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(art_paint_backList.get(i1)));
			}else if(currentFrase.contains(Constants.REALISM)){
				int i1 = r.nextInt(backList.size());
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(backList.get(i1)));
			}else if(currentFrase.contains(Constants.ART)){
				int i1 = r.nextInt(backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(backList.get(i1)));
			}else{
				int i1 = r.nextInt(backList.size()-1);
				mViewpagerLayout.setBackgroundDrawable(getResources().getDrawable(backList.get(i1)));
			}
		//	new LoadImageTask().execute(filePath);
		}
    }

    @Override
    protected void onDestroy() {
    	 if (adView != null) {
 	    	adView.destroy();
 	      }
    	Util.getInstance().saveCurrentFraseIndex();
    	super.onDestroy();
    }
    
    private void insertFile()
	{
		if (!Util.isSdPresent())
		{
			Toast.makeText(this, "NO SDCARD", Toast.LENGTH_SHORT).show();
			return;
		}
		
		Runnable r = new Runnable()
		{
			@Override
			public void run()
			{					
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);//
				startActivityForResult(Intent.createChooser(intent, "Select Picture"),FILE_BROWSING);
			}
		};
		r.run();
	}		
		
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data)
		{		
			super.onActivityResult(requestCode, resultCode, data);
			switch (requestCode)
			{
				case FILE_BROWSING:
					if (resultCode == RESULT_OK)
					{					
					     String filePath = null;
						 Uri selectedImageUri = data.getData();					
						 try {
		                        // OI FILE Manager
		                        String filemanagerstring = selectedImageUri.getPath();

		                        // MEDIA GALLERY
		                        String selectedImagePath = getPath(selectedImageUri);

		                        if (selectedImagePath != null) {
		                            filePath = selectedImagePath;
		                        } else if (filemanagerstring != null) {
		                            filePath = filemanagerstring;
		                        } 
		                        if (filePath != null) {
		                        	 setPostImageValues(data, filePath);
		                        } 
		                    } catch (Exception e) {
		                        Toast.makeText(getApplicationContext(), "Internal error", Toast.LENGTH_LONG).show();
		                    }						
					}
					break;
				default:
					break;
			}
		}
		
		public String getPath(Uri uri) {
	        String[] projection = { MediaStore.Images.Media.DATA };
	        Cursor cursor = managedQuery(uri, projection, null, null, null);
	        if(cursor!=null){
		        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		        cursor.moveToFirst();	        
		        return cursor.getString(column_index);
	        }
	        return null;
	    }
		
		 private void createShareIntent() {
			    Intent share = new Intent(Intent.ACTION_SEND);
			    share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			    share.putExtra(Intent.EXTRA_TEXT, "https://www.facebook.com/");
			    
			    // If you want to share a png image only, you can do:
			    // setType("image/png"); OR for jpeg: setType("image/jpeg");
			    share.setType("image/*");
			 
			    // Make sure you put example png image named myImage.png in your
			    // directory
			   
			 
			   
			    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			    
			    bmd.getBitmap().compress(Bitmap.CompressFormat.JPEG, 95, bytes);
			    String path = Images.Media.insertImage(getContentResolver(), bmd.getBitmap(), "img1", null);			    
			  //  Uri uri = Uri.fromFile();
			    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
			 startActivity(share);
			    //startActivity(Intent.createChooser(share, "Share Image!"));
		 }
		 
		private void setPostImageValues(Intent data, String imgFilePath) {		
			Bundle extras1 = data.getExtras();
			
			if(imgFilePath.equalsIgnoreCase("")){
				filePath = extras1.getString("ImageFilePath");	
			}else{
				filePath = imgFilePath;
			}				
			new LoadImageTask().execute(filePath);
		}
		
		
		private class LoadImageTask extends AsyncTask<String,Void,String>
	    {

	



			protected String doInBackground(String... params)
	        {
	       		Bitmap bm = ((BitmapDrawable)mViewpagerLayout.getBackground()).getBitmap();
	       		String text = Util.removeExtra(currentFrase);
        		bmd = ImagesTextWriter.getInstance().writeTextOnDrawable(bm, text, getApplicationContext());
	       	//	bm1 = ImagesTextWriter.getInstance().drawTextToBitmap(bm, currentFrase, getApplicationContext());
        		 createShareIntent();
			//	mPostImage.setImageBitmap(bm);	
				//mViewpagerLayout.setBackgroundDrawable((mPostImage.getDrawable()));
			    return null;
	        }

			@SuppressWarnings("deprecation")
			protected void onPostExecute(String result)
	        {
	        	try {        		
	         
				} catch (Exception e) {
				
				}        	        	               	         
	        }
	    }	

    
    private class ShowTextTask extends AsyncTask<String,Void,String>
    {
	    
        protected String doInBackground(String... params)
        {
        	SystemClock.sleep(3000);
        	return null;
        }

        protected void onPostExecute(String result)
        {
        	try {        					
        		 Toast.makeText(getApplicationContext(), "Pegue la frase", Toast.LENGTH_LONG).show();
			} catch (Exception e) {
			
			}        	        	               	         
        }
    }	

}